//
//  ThemeManager.swift
//  HeadlineNews
//
//  Created by han on 2019/7/22.
//  Copyright © 2019 han. All rights reserved.
//

import Foundation
// 可以使用数组初始化各个模板
// 可以使用Theme模板文件plist/txt初始化文件

// 当有一些控件的Theme不同主题，有的不变，有的改变时，可以用数组初始化固定。


class ThemeManager {
    
    static var animationDuration = 0.3
    static var currentThemeIndex: Int = 0
    static var currentTheme: NSDictionary?
    static var themeConfig: ThemeConfig?
    
}

extension ThemeManager {
    
    static func setTheme(dictionary: NSDictionary, themeConfig: ThemeConfig) {
        ThemeManager.currentTheme = dictionary
        ThemeManager.themeConfig = themeConfig
         NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
    }
    
    static func setTheme(name: String, themeConfig: ThemeConfig) {
        guard let dict = themeConfig.getData(from: name) else { return }
        self.setTheme(dictionary: dict, themeConfig: themeConfig)
    }
}

let ThemeUpdateNotification = "ThemeUpdateNotification"

struct  ThemeConfig {
    enum ThemeType: String {
        case plist = "plist"
        case txt = "txt"
        case json = "json"
    }
    
    enum ThemePath {
        case mainBundle
        case sandbox(Foundation.URL)
        
        func path(name: String, type: String) -> String? {
            switch self {
            case .mainBundle:
                return Bundle.main.path(forResource: name, ofType: "\(type)")
            case .sandbox(let path):
                let name = name.hasSuffix(".\(type)") ? name : name + ".\(type)"
                let url = path.appendingPathComponent(name)
                return url.path
            }
        }
    }
    
    var themeType: ThemeType = .plist
    var themePath: ThemePath = .mainBundle
    
    var url: Foundation.URL? {
        guard case ThemePath.sandbox(let url) = themePath else { return nil }
        return url
    }
    
    func getData(from name: String) -> NSDictionary? {
        
        guard let path = themePath.path(name: name, type: themeType.rawValue) else { return nil }
        
        switch themeType {
        case .plist:
            guard let plistDict = NSDictionary(contentsOfFile: path) else { return nil }
            return plistDict
        case .txt, .json:
            let url = URL(fileURLWithPath: path)
            do {
                let data = try! Data(contentsOf: url)
                return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions(rawValue: 0)]) as? NSDictionary
            } catch {
                return nil
            }
        }
    }
}
